export function Init() {
	return new Promise((resolve, reject) => {
		//使用uni.getProvider来获取通道
		uni.getProvider({
			service: 'payment',
			success: (res) => {
				let iapChannel = res.providers.find((channel) => {
					return (channel.id === 'appleiap')
				})
				//成功之后会返回通道
				resolve(iapChannel)
			},
		})
	})
}

export function restore(iapChannel) {
	console.log("获取苹果服务器已支付且未关闭的交易列表")
	return new Promise((resolve, reject) => {
		iapChannel.restoreCompletedTransactions({
			manualFinishTransaction: true,
			username: ''
		}, (res) => {
			resolve(res)
		}, (err) => {
			reject(err);
		})
	});
}
export function finishTransaction(transaction, iapChannel) {
	console.log("关闭订单",iapChannel)
	return new Promise((resolve, reject) => {
		iapChannel.finishTransaction(transaction, (res) => {
			console.log("关闭订单成功", res)
			resolve(res);
		}, (err) => {
			console.log('关闭订单失败',err);
			reject(err);
		});
	});
}

/**
 * 调用ID为“appleiap”的PaymentChannel对象的requestOrder方法，像Appstore请求有效的商品详情。
 * 注意：IAP支付必须在调用payment.request方法之前，调用requestOrder方法，否则调用payment.request将会报错。
 */
export function requestOrder(iapChannel, productIds) {
	uni.showLoading({
		title: '初始化中~',
		mask: true
	})
	return new Promise((resolve, reject) => {
		iapChannel.requestOrder(productIds, (orderList) => { //必须调用此方法才能进行 iap 支付
			console.log('requestOrder success: ' + JSON.stringify(orderList));
			resolve(orderList)
			uni.hideLoading()
		}, (e) => {
			console.log('requestOrder failed: ' + JSON.stringify(e));
			uni.hideLoading()
			uni.showToast({
				icon: 'none',
				title: '当前环境不支持内购支付'
			})
			reject(e)
		});
	})
}